import 'package:kegelutils/bean/bean_day_event.dart';
import 'package:kegelutils/storage/get_storage_instance.dart';

const String KEY_ADD_UP_DURATION = "key_add_up_duration";

class CalendarUtils {
  static void saveDateEvent(Event event) {
    int createTime = event.createTime!;
    DateTime createDateTime = DateTime.fromMillisecondsSinceEpoch(createTime);
    int year = createDateTime.year;
    int month = createDateTime.month;
    DateTime previousMon = DateTime(year, month);
    if (month == 12) {
      year += 1;
      month = 1;
    } else {
      month += 1;
    }
    DateTime nextMon = DateTime(year, month + 1);
    String monthKey =
        '${previousMon.millisecondsSinceEpoch}-${nextMon.millisecondsSinceEpoch}';

    String saveEventsValue = SpInstance.getInstance().getString(monthKey);
    DateEvents? dateEvent;
    if (saveEventsValue.isEmpty) {
      dateEvent = DateEvents.fromParams(
          createTime: DateTime.now().millisecondsSinceEpoch, events: [event]);
    } else {
      dateEvent = DateEvents(saveEventsValue);
      if (dateEvent.events == null) {
        dateEvent = DateEvents.fromParams(
            createTime: DateTime.now().millisecondsSinceEpoch, events: [event]);
      } else {
        dateEvent.events!.add(event);
      }
    }

    int addUpDuration =
        SpInstance.getInstance().getInt(KEY_ADD_UP_DURATION, defaultV: 0);
    addUpDuration += event.duration!;
    SpInstance.getInstance().setInt(KEY_ADD_UP_DURATION, addUpDuration);
    SpInstance.getInstance().setString(monthKey, dateEvent.toJson());
  }

  static DateEvents getDateEvents() {
    DateTime now = DateTime.now();
    int year = now.year;
    int month = now.month;
    DateTime previousMon = DateTime(year, month);
    if (month == 12) {
      year += 1;
      month = 1;
    } else {
      month += 1;
    }
    DateTime nextMon = DateTime(year, month + 1);
    String monthKey =
        '${previousMon.millisecondsSinceEpoch}-${nextMon.millisecondsSinceEpoch}';

    String saveEventsValue = SpInstance.getInstance().getString(monthKey);
    DateEvents? dateEvent;
    if (saveEventsValue.isEmpty) {
      dateEvent = DateEvents.fromParams(
          createTime: DateTime.now().millisecondsSinceEpoch, events: []);
    } else {
      dateEvent = DateEvents(saveEventsValue);
      if (dateEvent.events == null) {
        dateEvent = DateEvents.fromParams(
            createTime: DateTime.now().millisecondsSinceEpoch, events: []);
      }
    }
    return dateEvent;
  }
}
